﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QNetworkProxy>
#include <QtEndian>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , isInDataCollectionMode(false)
    , serialRingBuffer(nullptr)
{
    ui->setupUi(this);
    serialPort = new QSerialPort(this);
    tcpSocket = new QTcpSocket(this);
    
    // 创建环形缓冲区（8KB大小）
    serialRingBuffer = rngCreate(8192);
    if (!serialRingBuffer) {
        ui->textEdit->append("错误：无法创建环形缓冲区！");
    }
    
    initSerialPort();   // 初始化串口
    initTcpSocket();    // 初始化TCP套接字
    setupPlot();        // 初始化图表

    ui->Freq_lineEdit->setText("2450");
    ui->Span_lineEdit->setText("40");
    ui->time_lineEdit->setText("60");
}

MainWindow::~MainWindow()
{
    if (serialRingBuffer) {
        rngDelete(serialRingBuffer);
        serialRingBuffer = nullptr;
    }
    delete ui;
}


void MainWindow::setupPlot()
{
    //设置xy轴范围
    ui->widget_1024->xAxis->setRange(0,1024);
    ui->widget_1024->yAxis->setRange(0,100);
    ui->widget_1024->xAxis->setLabel("采样Index");
    ui->widget_1024->yAxis->setLabel("幅度");

    // 添加一个图形



    ui->widget_1024->addGraph();
    ui->widget_1024->graph(0)->setPen(QPen(Qt::red));
    ui->widget_1024->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);

    ui->widget_1024->replot();

}


void MainWindow::updatePortList()
{
    ui->portComboBox->clear();
    const auto infos = QSerialPortInfo::availablePorts();
    for (const QSerialPortInfo &info : infos) {
        ui->portComboBox->addItem(info.portName());
    }
}

void MainWindow::on_openButton_clicked()
{
    if (serialPort->isOpen()) {
           // 如果串口已打开，则关闭
           serialPort->close();
           ui->openButton->setText("打开串口");
       } else {
           // 如果串口没有打开，则打开
           serialPort->setPortName(ui->portComboBox->currentText());
           serialPort->setBaudRate(ui->baudComboBox->currentText().toInt());
           serialPort->setDataBits(QSerialPort::Data8);
           serialPort->setParity(QSerialPort::NoParity);
           serialPort->setStopBits(QSerialPort::OneStop);

           if (serialPort->open(QIODevice::ReadWrite)) {
               ui->openButton->setText("关闭串口");
           }
       }
}


void MainWindow::initSerialPort()
{
    // 初始化串口列表,将所有有用的串口添加到了下拉框
    updatePortList();
    
    // 初始化波特率列表
    ui->baudComboBox->addItems({"115200", "38400", "9600"});
    
    // 初始化数据位列表
    ui->dataComboBox->addItems({"8", "7", "6", "5"});
    
    // 初始化停止位列表
    ui->stopComboBox->addItems({"1", "1.5", "2"});

    // 连接信号和槽
    connect(serialPort, &QSerialPort::readyRead, this, &MainWindow::readData);
}

void MainWindow::initTcpSocket()
{
    // 连接TCP Socket的信号和槽
    connect(tcpSocket, &QTcpSocket::connected, this, [this]() {
        ui->tcpButton->setText("断开TCP");
        ui->receiveTextEdit->append("TCP连接成功！");
    });

    connect(tcpSocket, &QTcpSocket::disconnected, this, [this]() {
        ui->tcpButton->setText("连接TCP");
        ui->receiveTextEdit->append("TCP连接断开！");
    });

    connect(tcpSocket, &QTcpSocket::readyRead, this, [this]() {
        QByteArray data = tcpSocket->readAll();
        ui->receiveTextEdit->append(QString::fromUtf8(data));
        // 解析TCP接收到的消息
        QString message = QString::fromUtf8(data);
        findHeartbeat(message);
    });

    connect(tcpSocket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error),
        this, [this](QAbstractSocket::SocketError error) {
    Q_UNUSED(error);  // 告诉编译器这个参数是有意不使用的
    ui->receiveTextEdit->append("TCP错误: " + tcpSocket->errorString());
    });


    // 禁用代理
    tcpSocket->setProxy(QNetworkProxy::NoProxy);

    // 设置连接超时
    tcpSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);

    // 设置默认IP和端口
    ui->ipLineEdit->setText("192.168.4.112");
    ui->portLineEdit->setText("8899");
}


void MainWindow::readData()
{
    QByteArray data = serialPort->readAll();
    ui->receiveTextEdit->append(data);

    QString currentData = QString::fromUtf8(data);
    if (currentData.contains("S=")) {
        if(currentData.contains("M="))
        {
            parseMessageDirectly(currentData);
        }
    }

        if(isInDataCollectionMode)
        {
            uint8_t buff[sizeof(UAVRSSIDATA)] = {0};
            UAVRSSIDATA *rxHead = (UAVRSSIDATA *)buff;
            if (serialRingBuffer)
            {
                int bytesWritten = rngBufPut(serialRingBuffer, data.data(), data.size());
                if (bytesWritten < data.size()) {
                    ui->textEdit->append("警告：环形缓冲区已满，数据可能丢失！");
                } 
                // ui->textEdit->append(QString("=== 写入环形缓冲区：%1 字节 ===").arg(bytesWritten));
                // // 显示接收到的数据的十六进制内容（前20字节）
                // QString hexData = data.left(20).toHex(' ').toUpper();
                // ui->textEdit->append(QString("=== 数据内容(HEX): %1 ===").arg(hexData));
            }
            while(1)
            {
                size_t rnglen = rngNBytes(serialRingBuffer);    // 环形缓冲区里的数据长度
                if (rnglen < sizeof(HEAD_DATA_MESSAGE))
                {
                    return;
                }
                //ui->textEdit->append(QString("rnglen = %1").arg(rnglen));

                int r = rngBufGetNoDel(serialRingBuffer, (char*)buff, sizeof(HEAD_DATA_MESSAGE));
                if (rxHead->head != TXHead)
                {
                    rngBufGet(serialRingBuffer, (char*)buff, 1);
                    continue;
                }
                if ((rxHead->len) > sizeof(buff))//数据帧大小大于整个接收缓存则错误
                { 
                    rngBufGet(serialRingBuffer, (char*)buff, 1);
                    return;
                }

                if (rxHead->len > rngNBytes(serialRingBuffer))//数据帧大小大于整个环形缓存则错误
                    return;

                r = rngBufGet(serialRingBuffer, (char*)buff, rxHead->len);  //没有错误的话,取整个数据包,大小不够继续接收
                if (r != rxHead->len)
                    return;

                if(rxHead->id == 0x66)
                {
                    ui->textEdit->append("=== 收到UAV数据 ===");
                    ui->textEdit->append(QString("=== Freq: %1 ===").arg(rxHead->freq));
                    QVector<double> xData, yData;
                    for(int i = 0; i < 1024; i++) {
                        xData.append(i);
                        yData.append(rxHead->uavrssi[i]);
                        ui->widget_1024->graph(0)->setData(xData, yData);
                        
                    }
                    ui->widget_1024->replot();
                    ui->textEdit->append("测试数据已生成并显示在图表中");
                    return;
                }
            }
        }        

}



void MainWindow::findHeartbeat(const QString &data)
{
    // 查找S=开头的位置
    int startIndex = data.indexOf("S=");
    if (startIndex != -1) {
        // 从S=开始查找#C结束的位置
        int endIndex = data.indexOf("#C", startIndex);
        if (endIndex != -1) {
            // 提取完整的心跳包
            QString heartbeat = data.mid(startIndex, endIndex - startIndex + 2);
            // 解析心跳包
            parseMessage(heartbeat);
        }
    }
}

void MainWindow::parseMessageDirectly(const QString &message)
{
    // 查找M=的位置
    int mIndex = message.indexOf("M=");
    if (mIndex == -1) {
        ui->textEdit->append("未找到M=字段");
        return; // 没有找到M=字段
    }
    
    // 从M=后面开始查找下一个字段的开始位置
    int nextFieldIndex = message.indexOf("F=", mIndex);
    if (nextFieldIndex == -1) {
        // 如果没有F=字段，尝试查找其他可能的字段分隔符
        nextFieldIndex = message.indexOf("T=", mIndex);
        if (nextFieldIndex == -1) {
            // 如果还是没有，就取到字符串末尾
            nextFieldIndex = message.length();
        }
    }
    
    // 提取M=后面的值
    QString modeValue = message.mid(mIndex + 2, nextFieldIndex - mIndex - 2);
    ui->textEdit->append("提取的模式值: [" + modeValue + "]");
    
    // 解析模式值
    if(modeValue == "0")
    {
        ui->modeTextEdit->setText("侦测模式");
        ui->textEdit->append("=== 切换到侦测模式 ===");
        isInDataCollectionMode = false;  // 退出采数模式
    }
    else if(modeValue == "1")
    {
        ui->modeTextEdit->setText("敏捷打击");
        ui->textEdit->append("=== 切换到敏捷打击模式 ===");
    }
    else if(modeValue == "2")
    {
        ui->modeTextEdit->setText("采数模式");
        isInDataCollectionMode = true;  // 设置采数模式标志
        ui->textEdit->append("=== 进入采数模式，开始接收UAV数据 ===");
    }
    else if(modeValue == "3")
    {
        ui->modeTextEdit->setText("频点打击");
    }
    else
    {
        ui->textEdit->append("未知模式值: " + modeValue);
        isInDataCollectionMode = false;  // 其他模式也退出采数模式
    }
}



void MainWindow::parseMessage(const QString &message)
{
    // 检查消息格式：以S=开头，以#C结束
    if (!message.startsWith("S=") || !message.endsWith("#C")) {
        return; // 不是目标格式的消息，直接返回
    }
    
    int VIndex = message.indexOf("V=");
    
    // 查找M=的位置
    int mIndex = message.indexOf("M=");
    if (mIndex == -1) {
        return; // 没有找到M=字段
    }
    
    // 从M=后面开始查找下一个字段的开始位置
    int nextFieldIndex = message.indexOf("F=", mIndex);
    if (nextFieldIndex == -1) {
        return; // 没有找到F=字段
    }
    
    QString visionValue = message.mid(VIndex + 2, mIndex - VIndex - 2);
    ui->visionTextEdit->setText(visionValue);




    // 提取M=后面的值（从M=后面到F=前面）
    QString modeValue = message.mid(mIndex + 2, nextFieldIndex - mIndex - 2);
    
    if(modeValue == "0")
    {
        ui->modeTextEdit->setText("侦测模式");
        isInDataCollectionMode = false;  // 退出采数模式
    }
    else if(modeValue == "1")
    {
        ui->modeTextEdit->setText("敏捷打击");
    }
    else if(modeValue == "2")
    {
        ui->modeTextEdit->setText("采数模式");
        isInDataCollectionMode = true;  // 设置采数模式标志
        ui->textEdit->append("=== 进入采数模式，开始接收UAV数据 ===");
    }
    else if(modeValue == "3")
    {
        ui->modeTextEdit->setText("频点打击");
    }
    else
    {
        isInDataCollectionMode = false;  // 其他模式也退出采数模式
    }

}


void MainWindow::on_clearButton_clicked()
{
    ui->receiveTextEdit->clear();
    ui->textEdit->clear();
}

void MainWindow::on_sendButton_clicked()
{
    if(serialPort->isOpen())
    {
        QString text = ui->sendTextEdit->toPlainText();
        if(!text.isEmpty())
        {
            if(ui->hexCheckBox->isChecked()) {
                // HEX发送模式
                QByteArray hexData = QByteArray::fromHex(text.toUtf8());
                serialPort->write(hexData);
            } else {
                // 普通文本发送模式
                serialPort->write(text.toUtf8());
            }
        }
    }
}

void MainWindow::on_tcpButton_clicked()
{
    if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
        // 如果已连接，则断开
        tcpSocket->disconnectFromHost();
    } else {
        // 如果未连接，则连接
        QString ip = ui->ipLineEdit->text(); // 假设你有IP输入框
        int port = ui->portLineEdit->text().toInt();  // 假设你有端口输入框
        
        if (ip.isEmpty() || port <= 0) {
            ui->receiveTextEdit->append("请输入有效的IP地址和端口号！");
            return;
        }
        
        tcpSocket->connectToHost(ip, port);
        ui->receiveTextEdit->append("正在连接TCP服务器...");
    }
}

void MainWindow::on_cx_pushButton_clicked()
{
    QString hexString = "fbcdfbab03c51600000c01011900a816000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
    QByteArray hexData = QByteArray::fromHex(hexString.toUtf8());

    RXFREQ_DATA_MESSAGE tx_buff={};
    tx_buff.head=TXHead;
    tx_buff.id=freqlist_id;
    tx_buff.num=1;
    for (int i = 1, j = 0; j < (tx_buff.num); i+=3, j += 1)
    {
        tx_buff.data[i-1] = (uint16_t)0x19;    //时间
        tx_buff.data[i] = (uint16_t)ui->setfreq_textEdit->toPlainText().toUShort();
        tx_buff.data[i+1] = (uint16_t)0x00;
        tx_buff.sum += tx_buff.data[i-1];
        tx_buff.sum += tx_buff.data[i];
        tx_buff.sum += tx_buff.data[i+1];
    }
    
    // 计算校验和
    tx_buff.sum += (uint32_t)(tx_buff.id);
    tx_buff.sum += (uint32_t)(tx_buff.num);
    tx_buff.len=sizeof(RXFREQ_DATA_MESSAGE);

    // 将结构体转换为字节数组
    QByteArray structData(reinterpret_cast<const char*>(&tx_buff), sizeof(RXFREQ_DATA_MESSAGE));

    // 调试输出：显示结构体的十六进制内容
    qDebug() << "=== 发送的结构体数据 ===";
    qDebug() << "结构体大小:" << sizeof(RXFREQ_DATA_MESSAGE) << "字节";
    qDebug() << "Head:" << QString::number(tx_buff.head, 16).toUpper();
    qDebug() << "ID:" << QString::number(tx_buff.id, 16).toUpper();
    qDebug() << "Len:" << tx_buff.len;
    qDebug() << "Num:" << tx_buff.num;
    qDebug() << "Sum:" << QString::number(tx_buff.sum, 16).toUpper();
    qDebug() << "Data[0]:" << QString::number(tx_buff.data[0], 16).toUpper();
    qDebug() << "Data[1]:" << QString::number(tx_buff.data[1], 16).toUpper();
    qDebug() << "Data[2]:" << QString::number(tx_buff.data[2], 16).toUpper();
    
    // 显示完整的十六进制数据
    QString structHex = structData.toHex(' ').toUpper();
    qDebug() << "完整十六进制数据:" << structHex;
    
    // 显示硬编码的十六进制数据用于对比
    QString hardcodedHex = hexData.toHex(' ').toUpper();
    qDebug() << "硬编码十六进制数据:" << hardcodedHex;

    // 优先通过串口发送
    if(serialPort->isOpen()) {
        serialPort->write(structData);  // 发送结构体数据
        ui->receiveTextEdit->append("串口发送频点设置数据");
        ui->receiveTextEdit->append(QString("频率: %1").arg(tx_buff.data[1]));
    }
    else if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
        // 发送结构体数据
        tcpSocket->write(structData);  // 发送结构体数据
        ui->receiveTextEdit->append("TCP发送频点设置数据");
        ui->receiveTextEdit->append(QString("频率: %1").arg(tx_buff.data[1]));
     } else {
        ui->receiveTextEdit->append("串口和TCP都未连接，无法发送数据！");
     }
}

void MainWindow::on_exitcx_pushButton_clicked()
{
    QString hexString = "fbcdfbab03030000000c010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
    QByteArray hexData = QByteArray::fromHex(hexString.toUtf8());
    // 优先通过串口发送
    if(serialPort->isOpen()) {
        serialPort->write(hexData);
        ui->receiveTextEdit->append("串口发送十六进制数据: " + hexString);
        //ui->modeTextEdit->setText("侦测模式");
    }
    else if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
        // 发送十六进制数据
        tcpSocket->write(hexData);
        ui->receiveTextEdit->append("发送十六进制数据: " + hexString);
     } else {
        ui->receiveTextEdit->append("TCP未连接，无法发送数据！");
     }
}



void MainWindow::on_IAPpushButton_clicked()
{
    QString hexString = "48460000200000002d00000001000000170000000000000000000000ad460000";
    QByteArray hexData = QByteArray::fromHex(hexString.toUtf8());
    // 优先通过串口发送
    if(serialPort->isOpen()) {
        serialPort->write(hexData);
        ui->receiveTextEdit->append("串口发送十六进制数据: " + hexString);
        ui->modeTextEdit->setText("InIAP");
    }
    else if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
        // 发送十六进制数据
        tcpSocket->write(hexData);
        ui->receiveTextEdit->append("发送十六进制数据: " + hexString);
        ui->modeTextEdit->setText("InIAP");
     } else {
        ui->receiveTextEdit->append("TCP未连接，无法发送数据！");
     }
}

void MainWindow::on_APPpushButton_clicked()
{
    QString hexString = "48460000180000002d0000000100000014000000a2460000";
    QByteArray hexData = QByteArray::fromHex(hexString.toUtf8());
    // 优先通过串口发送
    if(serialPort->isOpen()) {
        serialPort->write(hexData);
        ui->receiveTextEdit->append("串口发送十六进制数据: " + hexString);
        ui->modeTextEdit->setText("InAPP");
    }
    // 如果串口未连接，尝试通过TCP发送
    else if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
        // 发送十六进制数据
        tcpSocket->write(hexData);
        ui->receiveTextEdit->append("发送十六进制数据: " + hexString);
        ui->modeTextEdit->setText("InAPP");
     } else {
        ui->receiveTextEdit->append("TCP未连接，无法发送数据！");
     }
}





void MainWindow::on_expandfreq_Button_clicked()
{
    isExpanded=!isExpanded;
    if(isExpanded)
    {
        ui->expandfreq_Button->setText("退扩频模式");
        TX_DATA_MESSAGE tx_buff={};
        tx_buff.head=0xABFBCDFB;
        tx_buff.id=0x25;
        tx_buff.data=0x01;
        tx_buff.sum=tx_buff.id + tx_buff.data;
        tx_buff.len=sizeof(TX_DATA_MESSAGE);
        tx_buff.tail=0x0FAFBFCF;
        if(serialPort->isOpen())
        {
            QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(TX_DATA_MESSAGE));
            serialPort->write(data);
        }else if (tcpSocket->state() == QAbstractSocket::ConnectedState)
        {
            QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(TX_DATA_MESSAGE));
            tcpSocket->write(data);
         }
    }
    else
    {
        ui->expandfreq_Button->setText("进扩频模式");
        TX_DATA_MESSAGE tx_buff={};
        tx_buff.head=0xABFBCDFB;
        tx_buff.id=0x25;
        tx_buff.data=0x00;
        tx_buff.sum=tx_buff.id + tx_buff.data;
        tx_buff.len=sizeof(TX_DATA_MESSAGE);
        tx_buff.tail=0x0FAFBFCF;
        if(serialPort->isOpen())
        {
            QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(TX_DATA_MESSAGE));
            serialPort->write(data);
        }else if (tcpSocket->state() == QAbstractSocket::ConnectedState)
        {
            QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(TX_DATA_MESSAGE));
            tcpSocket->write(data);
         }
    }

}




void MainWindow::on_in_mjmode_pushButton_clicked()
{
    TX_DATA_MESSAGE tx_buff={};
    tx_buff.head=TXHead;
    tx_buff.id=agility_id;
    tx_buff.data=agility_on;
    tx_buff.sum=tx_buff.id + tx_buff.data;
    tx_buff.len=sizeof(TX_DATA_MESSAGE);
    tx_buff.tail=TXTial;
    if(serialPort->isOpen())
    {
        QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(TX_DATA_MESSAGE));
        serialPort->write(data);
    }else if (tcpSocket->state() == QAbstractSocket::ConnectedState)
    {
        QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(TX_DATA_MESSAGE));
        tcpSocket->write(data);
    }
}





void MainWindow::on_exit_mjmode_pushButton_clicked()
{
    TX_DATA_MESSAGE tx_buff={};
    tx_buff.head=TXHead;
    tx_buff.id=agility_id;
    tx_buff.data=agility_off;
    tx_buff.sum=tx_buff.id + tx_buff.data;
    tx_buff.len=sizeof(TX_DATA_MESSAGE);
    tx_buff.tail=TXTial;
    if(serialPort->isOpen())
    {
        QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(TX_DATA_MESSAGE));
        serialPort->write(data);
    }else if (tcpSocket->state() == QAbstractSocket::ConnectedState)
    {
        QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(TX_DATA_MESSAGE));
        tcpSocket->write(data);
    }
}

void MainWindow::on_Jam_pushButton_clicked()
{
    USER_SETAGILITYFREQ tx_buff={};

    tx_buff.head=TXHead;
    tx_buff.id=usersetagility_id;
    tx_buff.freq=ui->Freq_lineEdit->text().toUShort();
    tx_buff.span=ui->Span_lineEdit->text().toUShort();
    tx_buff.time_s=ui->time_lineEdit->text().toUShort();
    tx_buff.sum=tx_buff.id+tx_buff.freq;
    tx_buff.len=sizeof(USER_SETAGILITYFREQ);
    tx_buff.tail=TXTial;

    if(serialPort->isOpen())
    {
        QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(USER_SETAGILITYFREQ));
        serialPort->write(data);
    }else if (tcpSocket->state() == QAbstractSocket::ConnectedState)
    {
        QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(USER_SETAGILITYFREQ));
        tcpSocket->write(data);
    }
    QString formattedText = QString("打击频点: %1 MHz  带宽: %2 MHz  时长: %3 s")
    .arg(tx_buff.freq)
    .arg(tx_buff.span)
    .arg(tx_buff.time_s);
    ui->textEdit->setPlainText(formattedText);
}

void MainWindow::on_exit_JampushButton_clicked()
{
    USER_SETAGILITYFREQ tx_buff={};

    tx_buff.head=TXHead;
    tx_buff.id=usersetagility_id;
    tx_buff.freq=0;
    tx_buff.span=ui->Span_lineEdit->text().toUShort();
    tx_buff.time_s=ui->time_lineEdit->text().toUShort();
    tx_buff.sum=tx_buff.id+tx_buff.freq;
    tx_buff.len=sizeof(USER_SETAGILITYFREQ);
    tx_buff.tail=TXTial;

    if(serialPort->isOpen())
    {
        QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(USER_SETAGILITYFREQ));
        serialPort->write(data);
    }else if (tcpSocket->state() == QAbstractSocket::ConnectedState)
    {
        QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(USER_SETAGILITYFREQ));
        tcpSocket->write(data);
    }
    ui->textEdit->setPlainText("=== 退出打击模式 ===");

}

void MainWindow::on_Jam_pushButton_2_clicked()
{
    USER_SETAGILITYFREQ_gai tx_buff={};

    tx_buff.head=TXHead;
    tx_buff.id=usersetagility_id;
    tx_buff.freq[0]=ui->Freq_lineEdit->text().toUShort();
    tx_buff.span[0]=ui->Span_lineEdit->text().toUShort();
    tx_buff.time_s[0]=ui->time_lineEdit->text().toUShort();
    tx_buff.sum=tx_buff.id+tx_buff.freq[0];
    tx_buff.len=sizeof(USER_SETAGILITYFREQ_gai);
    tx_buff.tail=TXTial;

    if(serialPort->isOpen())
    {
        QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(USER_SETAGILITYFREQ_gai));
        serialPort->write(data);
    }else if (tcpSocket->state() == QAbstractSocket::ConnectedState)
    {
        QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(USER_SETAGILITYFREQ_gai));
        tcpSocket->write(data);
    }
    QString formattedText = QString("打击频点: %1 MHz  带宽: %2 MHz  时长: %3 s")
    .arg(tx_buff.freq[0])
    .arg(tx_buff.span[0])
    .arg(tx_buff.time_s[0]);
    ui->textEdit->setPlainText(formattedText);
}

void MainWindow::on_exit_JampushButton_2_clicked()
{
    USER_SETAGILITYFREQ_gai tx_buff={};

    tx_buff.head=TXHead;
    tx_buff.id=usersetagility_id;
    tx_buff.freq[0]=0;
    tx_buff.span[0]=ui->Span_lineEdit->text().toUShort();
    tx_buff.time_s[0]=ui->time_lineEdit->text().toUShort();
    tx_buff.sum=tx_buff.id+tx_buff.freq[0];
    tx_buff.len=sizeof(USER_SETAGILITYFREQ_gai);
    tx_buff.tail=TXTial;

    if(serialPort->isOpen())
    {
        QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(USER_SETAGILITYFREQ_gai));
        serialPort->write(data);
    }else if (tcpSocket->state() == QAbstractSocket::ConnectedState)
    {
        QByteArray data(reinterpret_cast<const char*>(&tx_buff), sizeof(USER_SETAGILITYFREQ_gai));
        tcpSocket->write(data);
    }
    QString formattedText = QString("打击频点: %1 MHz  带宽: %2 MHz  时长: %3 s")
    .arg(tx_buff.freq[0])
    .arg(tx_buff.span[0])
    .arg(tx_buff.time_s[0]);
    ui->textEdit->setPlainText(formattedText);
}
